﻿Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Data.Linq
Imports System.Text
Imports DevComponents
Imports System.Data
Imports System.Text.RegularExpressions
Imports TNCDAL
Imports HTLibrary

Public Class ucChiPhiXangDau

    Dim moil As New MOilPrice
    Dim util As New Utilities
    Dim munitprice As New MOilUnitPrices
    Dim col1 As DataGridViewTextBoxColumn
    Dim col2 As DataGridViewComboBoxColumn
    Dim col3 As DevComponents.DotNetBar.Controls.DataGridViewDateTimeInputColumn
    Dim TotRowCount As Integer
    Private NewTruckID As Integer
    Private isNewOilExpense As Boolean
    Private isEditOilExpese As Boolean
    Dim blnLocthang As Boolean = False
    Dim blnLocquy As Boolean = False
    Dim blnLocnam As Boolean = False
    Dim filterTab1 As Boolean = False
    Dim blnLocthang2 As Boolean = False
    Dim blnLocquy2 As Boolean = False
    Dim blnLocnam2 As Boolean = False
    Dim blnLocSoxe2 As Boolean = False
    Dim blnLocTaixe2 As Boolean = False
    Dim filterTab2 As Boolean = False
    Dim _isNewOilPayment As Boolean = False
    Dim _isEditOilPayment As Boolean = False
    Dim isLoadcbMonth As Boolean = False
    Dim isLoadcbYear As Boolean = False
    Dim moilPay As New MOilPayments

    Dim TotRowCountOidPayment As Integer
    Dim RowId As Integer
    Dim EditRowIndex As Integer = 0
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()
        DataGridViewHelper.DataGridView_InitEvent(gridOilManager)

        ' Add any initialization after the InitializeComponent() call.

    End Sub
    Sub LoadImportir()
        ' util.FillDriverCombo(col2)
        util.FillDriverCombo(cbgridSign)
        util.FillDriverCombo(cbSign)
        util.FillTruckCombo(cbTruck)
        util.FillTruckCombo(cbTruckNo)
        util.FillDriverCombo(cbDriver)
        util.FillDriverCombo(cbDriverName)
        datePushOil.CustomFormat = "dd/MM/yyyy"
        datePushOil.Value = Date.Now()
    End Sub

    Sub bindingTogrid()
        Dim query = moil.getOilfeulList3()

        Dim source As New BindingSource
        source.DataSource = query
        BindingNavigator1.BindingSource = source
        gridOilManager.DataSource = source
        gridOilManager.Columns(0).ReadOnly = True
        TotRowCount = gridOilManager.RowCount - 1
        gridOilManager.Rows(EditRowIndex).Selected = True
    End Sub
    Private Sub ResetControl()
        datePushOil.Value = DateTime.Now()
        txtOilLiter.Text = ""
        txtUnitPrice.Text = ""
        txtSumMoney.Text = ""
        cbTruckNo.SelectedIndex = 0
        cbDriver.SelectedIndex = 0
        cbSign.SelectedIndex = 0

    End Sub
    Sub EnableOilExpenseControl(ByVal value As Boolean, ByVal addnew As Boolean)
        txtOilLiter.Enabled = value
        txtUnitPrice.Enabled = value
        cbTruckNo.Enabled = value
        cbDriver.Enabled = value
        cbSign.Enabled = value
        '  datePushOil.Enabled = value
        btnSaveOilExpense.Enabled = value
        datePushOil.Enabled = value
        If value And isNewOilExpense Then
            datePushOil.Value = DateTime.Now()
            txtOilLiter.Text = ""
            'Kiểm tra dữ liệu giá theo ngày. nếu ngày hôm nay không có trong dữ liệu
            'sắp xếp giá và lấy giá của ngày gần với ngày hôm nay nhất

            If datePushOil.Value.ToShortDateString() IsNot Nothing Then
                txtUnitPrice.Text = munitprice.getPriceCurrent(datePushOil.Value.ToShortDateString())
            Else
                MessageBox.Show("Chọn ngày đổ dầu để có giá tham khảo?")
                Return
            End If
        Else
            If value And isEditOilExpese Then
                'Nếu sửa

                If datePushOil.Value.ToShortDateString() IsNot Nothing And txtUnitPrice.Text = "" Then
                    txtUnitPrice.Text = munitprice.getPriceCurrent(datePushOil.Value.ToShortDateString())
                Else
                    'MessageBox.Show("Chọn ngày đổ dầu để có giá tham khảo?")
                    Return
                End If
            End If
        End If

    End Sub

    Private Sub btnAddUnitPrice_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim newprice As New FrmUnitPrice
        newprice.ShowDialog()
        util.FillDriverCombo(cbTruckNo)
    End Sub

    Private Function FormatMoney(ByVal money As Object) As String
        Dim str As String = money.ToString()
        Dim pattern As String = "(?<a>\d*)(?<b>\d{3})*"
        Dim m As Match = Regex.Match(str, pattern, RegexOptions.RightToLeft)
        Dim sb As StringBuilder = New StringBuilder

        For Each i As Capture In m.Groups("b").Captures
            sb.Insert(0, "." + i.Value)
        Next

        sb.Insert(0, m.Groups("a").Value)
        Return sb.ToString().Trim(".")

    End Function

    Private Sub btnInsertOilPayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
     
    End Sub

    Private Sub btnAddOilExpense_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddOilExpense.Click
        isNewOilExpense = True
        isEditOilExpese = False
        EditRowIndex = 0
        EnableOilExpenseControl(True, True)
        btnAddOilExpense.Enabled = False
        btnEditOilExpense.Enabled = False
        btnDeleteOilExpense.Enabled = False
        btnSaveOilExpense.Enabled = True
        btncancel.Enabled = True
        txtOilLiter.Focus()
        gridOilManager.Enabled = False
    End Sub

    Private Sub btnNewTruck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim newtruck As New ucTruck
        frmMain.AddNewDockContainerItem("NewTruck", "New Truck", newtruck)
        util.FillTruckCombo(cbTruckNo)
    End Sub

    Private Sub btnSaveOilExpense_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveOilExpense.Click
        'lưu thông tin mới

        If isNewOilExpense Then
            Dim objoil As New tblOilfuel

            If Not IsDBNull(txtOilLiter.Text) And Not IsDBNull(txtUnitPrice.Text) And Not IsDBNull(cbTruckNo.SelectedIndex) _
                And Not IsDBNull(datePushOil.Value) Then
                objoil.UnitPrice = txtUnitPrice.Text.Replace(".", "")
                objoil.Liter = txtOilLiter.Text
                objoil.DatePush = datePushOil.Value.ToShortDateString()
                objoil.ID_Truck = cbTruckNo.SelectedValue
                objoil.ID_Driver = cbDriver.SelectedValue
                objoil.ID_Sign = cbSign.SelectedValue
                moil.InsertNewRecord(objoil)

            End If
            bindingTogrid()

        Else
            Dim objoil As New tblOilfuel

            If Not IsDBNull(txtOilLiter.Text) And Not IsDBNull(txtUnitPrice.Text) And Not IsDBNull(cbTruckNo.SelectedIndex) _
                And Not IsDBNull(datePushOil.Value) Then
                objoil.ID_Oilfuel = txtIDOilFuel.Text
                objoil.UnitPrice = txtUnitPrice.Text.Replace(".", "")
                objoil.Liter = txtOilLiter.Text
                objoil.DatePush = datePushOil.Value.ToShortDateString()
                objoil.ID_Truck = cbTruckNo.SelectedValue
                objoil.ID_Driver = cbDriver.SelectedValue
                objoil.ID_Sign = cbSign.SelectedValue
                moil.UpdateRecord(objoil)
            
            End If
            bindingTogrid()
            gridOilManager.Rows(EditRowIndex).Selected = True
            gridOilManager.FirstDisplayedScrollingRowIndex = EditRowIndex
            gridOilManager.CurrentCell = gridOilManager(1, EditRowIndex)
            ' lblMsg.Visible = True
        End If
        isNewOilExpense = False
        isEditOilExpese = False
        EnableOilExpenseControl(False, False)
        btnAddOilExpense.Enabled = True
        btnEditOilExpense.Enabled = True
        btnDeleteOilExpense.Enabled = True
        btnSaveOilExpense.Enabled = False
        btncancel.Enabled = False
          gridOilManager.Enabled = True
    End Sub

    Private Sub btnDeleteOilExpense_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteOilExpense.Click

        If (MessageBox.Show("Do you really want to delete selected record?",
             "Delete Warning", MessageBoxButtons.YesNo,
             MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2, 0, False) = DialogResult.Yes) Then


            Dim id As Integer = Convert.ToInt32(txtIDOilFuel.Text)

            If id <> 0 Then
                moil.DeleteRecord(id)
            End If

           
        End If
       
        bindingTogrid()


        If gridOilManager.RowCount <= 0 Then
            'Xóa sạch các trường
            ResetField()
        End If

        EnableOilExpenseControl(False, False)
        btnAddOilExpense.Enabled = True
        btnEditOilExpense.Enabled = True
        btnDeleteOilExpense.Enabled = True
        btnSaveOilExpense.Enabled = False
        btncancel.Enabled = False
    End Sub

    Private Sub ResetField()
        datePushOil.Value() = DateTime.Now()
        txtOilLiter.Text = ""
        txtUnitPrice.Text = ""
        txtPricePrice.Text = ""
        cbTruckNo.SelectedIndex = 0
        cbDriver.SelectedIndex = 0
        cbSign.SelectedIndex = 0
        txtSumMoney.Text = ""
        txtIDOilFuel.Text = ""
    End Sub

    Private Sub txtUnitPrice_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtUnitPrice.TextChanged
        util.FormatCurr(txtUnitPrice)
        Try
            Dim lit As Integer = Convert.ToInt32(txtOilLiter.Text)
            Dim prices As String = txtUnitPrice.Text
            prices = prices.Replace(",", "")
            Dim price As Integer = Convert.ToInt32(prices)
            Dim sum As Integer = lit * price
            txtSumMoney.Text = sum
        Catch ex As Exception

        End Try
    End Sub

    Private Sub txtSumMoney_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSumMoney.TextChanged
        util.FormatCurr(txtSumMoney)
    End Sub

    Private Sub gridOilManager_RowEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridOilManager.RowEnter
        Dim rw As Integer = e.RowIndex
        Dim dg As DataGridView = CType(sender, DataGridView)
        txtIDOilFuel.Text = dg.Item(0, rw).Value   'row.Item("id").ToString
        If dg.Item(1, rw).Value IsNot Nothing Then

            datePushOil.Value = dg.Item(1, rw).Value
        End If
        txtOilLiter.Text = dg.Item(2, rw).Value 'row.Item("caption").ToString
        txtUnitPrice.Text = dg.Item(3, rw).Value 'row.Item("menu_desc").ToString
        'Thành tiền
        If dg.Item(4, rw).Value IsNot Nothing Then

            txtSumMoney.Text = dg.Item(4, rw).Value
        End If
        If dg.Item(5, rw).Value IsNot Nothing Then

            cbTruckNo.SelectedValue = dg.Item(5, rw).Value
        End If
        If dg.Item(6, rw).Value IsNot Nothing Then

            cbDriver.SelectedValue = dg.Item(6, rw).Value
        End If
        If dg.Item(7, rw).Value IsNot Nothing Then

            cbSign.SelectedValue = dg.Item(7, rw).Value
        End If
    End Sub

    Private Sub btncancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncancel.Click

        If gridOilManager.RowCount <= 0 Then
            ResetField()
        End If

        If isNewOilExpense Then
            '  btnAddNewTruck.Text = "Thêm"
            isNewOilExpense = False

        ElseIf isEditOilExpese Then

            '   btnAddNewTruck.Text = "Thêm"
            '    btnEditTruck.Text = "Sửa"
            isEditOilExpese = False
        End If

        EnableOilExpenseControl(False, False)
        btnAddOilExpense.Enabled = True
        btnEditOilExpense.Enabled = True
        btnDeleteOilExpense.Enabled = True
        btnSaveOilExpense.Enabled = False
        btncancel.Enabled = False
        gridOilManager.Enabled = True
        bindingTogrid()
    End Sub

    Private Sub btnEditOilExpense_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditOilExpense.Click
        EditRowIndex = gridOilManager.CurrentRow.Index
        'gridOilManager.ReadOnly = True
        If txtIDOilFuel.Text = "" Then
            Return
        End If

        isEditOilExpese = True

        EnableOilExpenseControl(True, True)
        btnAddOilExpense.Enabled = False
        btnEditOilExpense.Enabled = False
        btnDeleteOilExpense.Enabled = False
        btnSaveOilExpense.Enabled = True
        btncancel.Enabled = True
        gridOilManager.Enabled = False
        txtOilLiter.Focus()
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        _isNewOilPayment = True
        _isEditOilPayment = False

    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        _isEditOilPayment = True
        _isNewOilPayment = False

    End Sub
    
    Private Sub gridOilPayment_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs)

    End Sub

    Private Sub btnLoc1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Nút lọc thông tin chi trả tiền xăng dầu cho hãng
        filterTab1 = True

    End Sub

    Private Sub btnAddUnitPrice_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Dim frm As New FrmUnitPrice
        'frm.ShowDialog()
        ''sau khi nhập giá mới sẽ lấy giá mới nhất chèn vào 
        'Dim mOUnitPrice As New MOilUnitPrices
        'Dim newestPrice As Integer = mOUnitPrice.getNewestPriceFile()
        'Me.txtUnitPrice.Text = newestPrice
        ExpandablePanelUnitPrice.Expanded = True
        datePrice.Value = DateTime.Now()
    End Sub

    Private Sub txtOilLiter_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtOilLiter.TextChanged

        Try
            Dim lit As Integer = Convert.ToInt32(txtOilLiter.Text)
            Dim prices As String = txtUnitPrice.Text
            prices = prices.Replace(",", "")
            Dim price As Integer = Convert.ToInt32(prices)
            Dim sum As Integer = lit * price
            txtSumMoney.Text = sum
        Catch ex As Exception

        End Try
    End Sub

    Private Sub btnCancelPayment_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        _isEditOilPayment = False
        _isNewOilPayment = False

    End Sub

    Private Sub btnBoLoc2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Bỏ  lọc tab chi tiết mua xăng dầu

    End Sub

    Private Sub gridTotalMonth_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs)
        Dim gridView As DataGridView = CType(sender, DataGridView)

        If gridView IsNot Nothing Then
            For Each r As DataGridViewRow In gridView.Rows
                gridView.Rows(r.Index).HeaderCell.Value = (r.Index + 1).ToString()
            Next

        End If

    End Sub

    Private Sub btnChonGia_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChonGia.Click
        ' Chèn giá vào cơ sở dữ liệu và nếu thành công thì thêm vào giá mới
        Try
            Dim mUnitPrice As New MOilUnitPrices
            Dim obj As New tblOilUnitPrice
            obj.UnitPrice = txtPricePrice.Text
            obj.DateChange = datePrice.Value
            obj.Description = txtNotePrice.Text
            mUnitPrice.InsertNewRecord(obj)

        Catch ex As Exception

        End Try
        'Chèn thành công
        txtUnitPrice.Text = txtPricePrice.Text
        ExpandablePanelUnitPrice.Expanded = False
        txtUnitPrice.Focus()
    End Sub

    Private Sub ucChiPhiXangDau_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'cbTruckNo.AutoCompleteMode = AutoCompleteMode.Append
        cbTruckNo.DropDownStyle = ComboBoxStyle.DropDown
        cbTruckNo.AutoCompleteMode = AutoCompleteMode.Suggest
        cbTruckNo.AutoCompleteSource = AutoCompleteSource.ListItems
        cbDriver.DropDownStyle = ComboBoxStyle.DropDown
        cbDriver.AutoCompleteMode = AutoCompleteMode.Suggest
        cbDriver.AutoCompleteSource = AutoCompleteSource.ListItems

        gridOilManager.EditMode = DataGridViewEditMode.EditOnEnter
   
        LoadImportir()
        bindingTogrid()
 
        EnableOilExpenseControl(False, False)
        isNewOilExpense = False
    End Sub

    Private Sub txtPricePrice_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPricePrice.TextChanged
        util.FormatCurr(txtPricePrice)
    End Sub

    Private Sub btnNewPrice_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewPrice.Click
        ExpandablePanelUnitPrice.Expanded = True
        datePrice.Value = DateTime.Now()
        txtPricePrice.Focus()
    End Sub

    Private Sub gridOilManager_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles gridOilManager.DataBindingComplete
        'Kiểm tra nếu mà không có dữ liệu thì cho 2 nút edit và delete ẩn

        If gridOilManager.RowCount > 0 Then
            btnEditOilExpense.Enabled = True
            btnDeleteOilExpense.Enabled = True
        Else
            ResetControl()
            btnEditOilExpense.Enabled = False
            btnDeleteOilExpense.Enabled = False
        End If

    End Sub

     
    Private Sub txtOilLiter_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtOilLiter.KeyPress
        If (Not (Char.IsControl(e.KeyChar) Or Char.IsDigit(e.KeyChar))) Then
            e.Handled = True
        End If
    End Sub

    Private Sub txtUnitPrice_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtUnitPrice.KeyPress
        If (Not (Char.IsControl(e.KeyChar) Or Char.IsDigit(e.KeyChar))) Then
            e.Handled = True
        End If
    End Sub
End Class

